package com.last.controller;

import com.api.order.OrderClient;
import com.github.wxpay.sdk.WXPayUtil;
import com.last.config.MyConfig;
import com.last.config.WebSocketServer;
import com.last.entity.Order;
import com.last.entity.Result;
import com.last.service.PayService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
public class PayController  {

    @Resource
    private PayService payService;

    @Resource
    private OrderClient orderClient;


    @RequestMapping("/order")
    public Result order(String orderId){

        return payService.pay(orderId);
    }


    @RequestMapping("/notify")
    public String  notify(HttpServletRequest request) {
        InputStream inStream;
        try {
            inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");
            System.out.println(result);

            //对xml进行解析 map
            Map<String, String> map = WXPayUtil.xmlToMap(result);
            //验证签名
            boolean signatureValid = WXPayUtil.isSignatureValid(map,
                    new MyConfig().getKey());


            System.out.println("验证签名是否正确：" + signatureValid);
            System.out.println(map.get("out_trade_no"));//订单号
            String orderId = map.get("out_trade_no");
            String total_fee = map.get("total_fee");
            System.out.println(map.get("result_code"));

            if (signatureValid && "SUCCESS".equals(map.get("result_code"))) {
                //修改订单状态(支付状态、订单状态、支付时间、修改时间)
                Order order = new Order();
                order.setOrderId(orderId);
                order.setUpdateTime(new Date());
                order.setOrderStatus(1);
                orderClient.status(order);


                Map data = new HashMap();
                data.put("return_code", "SUCCESS");
                data.put("return_msg", "OK");

                //map转xml
                String returnXml = WXPayUtil.generateSignedXml(data, new MyConfig().getKey());


                //给客户端（浏览器）发消息,告诉客户端已经支付成功
                WebSocketServer.sendMessageToClient(orderId, "success");

                return returnXml;
            }


        } catch (Exception e) {
            e.printStackTrace();

        }

        return "";
    }

}
